#include "cpumonitor.h"
#include <QDateTime>

CPUMonitor::CPUMonitor(QObject *parent)
    : QObject(parent)
{
    // 初始化数据
    currentData.total = 0.0;
    currentData.user = 0.0;
    currentData.system = 0.0;
    currentData.idle = 0.0;
    currentData.timestamp = QDateTime::currentMSecsSinceEpoch();

    dataThread = new DataCollectionThread(this);

    // 线程统计完之后发送信号，给监控器处理
    connect(dataThread, &DataCollectionThread::dataUpdated, this, &CPUMonitor::onDataCollected);

    // 启动监控
    startMonitoring();
}

CPUMonitor::~CPUMonitor()
{
    stopMonitoring();
}

void CPUMonitor::startMonitoring()
{
    //存在对象，并且该对象没有在运行
    if (dataThread && !dataThread->isRunning()) {
        dataThread->start();
        qDebug() << "CPU监控启动";
    }
}

void CPUMonitor::stopMonitoring()
{
    if (dataThread && dataThread->isRunning()) {
        dataThread->stopThread();
        dataThread->wait(); // 等待线程结束
        qDebug() << "CPU监控停止";
    }
}

void CPUMonitor::onDataCollected(CPUData data)
{
    // 更新当前数据
    currentData = data;

    // 发送数据更新信号
    emit dataUpdated(data);
}



